package com.salton123.soulove.sailfish.video.task

import android.os.Environment
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.ThreadUtils
import com.salton123.log.XLog
import com.salton123.soulove.app.BuildConfig
import com.salton123.soulove.sailfish.video.SailfishManager
import com.salton123.soulove.sailfish.video.SailfishManager.coroutineScope
import com.salton123.soulove.utils.Utils
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import java.io.File

/**
 * Time:2021/8/24 6:13 下午
 * Author:
 * Description:
 */
class MediaFileScanTask : IBackgroundTask {
    private val pathName = Environment.getExternalStorageDirectory().absolutePath
    private val TAG = "MediaFileScanTask"

    override fun launch() {
        coroutineScope.launch {
            File(pathName).listFiles()?.forEach { stubFile ->
                if (stubFile.isFile) {
                    assembleVideoInfo(stubFile)
                } else if (stubFile.isDirectory) {
                    ThreadUtils.executeByCached(object : SimpleTaskCallback() {
                        override fun doInBackground() {
                            stubFile.walkTopDown().maxDepth(Int.MAX_VALUE).forEach { file ->
                                assembleVideoInfo(file)
                            }
                        }
                    })
                }
            }
        }
    }

    /**
     * 从file中装配视频文件信息
     */
    fun assembleVideoInfo(file: File) {
        try {
            val filePath = file.absolutePath
            if (Utils.filterVideoBySuffix(file)) {
                SailfishManager.videoList?.find { it.filePath == filePath }?.let {
                    XLog.i(TAG, "find the same item:${filePath}")
                    if (!FileUtils.isFileExists(filePath)) {
                        coroutineScope.async {
                            SailfishManager.deleteVideo(it)
                        }
                    }
                } ?: kotlin.run {
                    val videoItem = Utils.retrieveFile(file)
                    Utils.saveToDb(videoItem)
                }
            } else {
                if (BuildConfig.APP_DEVELOP) {
                    XLog.d(TAG, "assembleVideoInfo:${filePath}")
                }
            }
        } catch (ex: Throwable) {
            ex.printStackTrace()
        }
    }
}